<template>
  <div class="b-customized-widget relative flex flex-col overflow-hidden h-full">
    <div class="b-customized-widget__wrapper flex-1 h-0 relative overflow-auto"
         :style="{
                  'grid-template-columns':  `repeat(${columns}, ${itemStyle.width})`,
                  'grid-template-rows':  `repeat(${rows}, ${itemStyle.height})`
              }">
      <BCustomizedWidgetItem v-for="(item,index) in options"
                             :key="index"
                             :title="item.title"
                             :itemStyle="itemStyle"
                             :description="item.introduction"
                             :icon="item.imageUrl"
                             @click.stop="onSelected(item)" />
    </div>

    <div :class="['flex b-customized-widget-pagination items-center',currentPosition]"
         v-if="pagination">
      <el-pagination :current-page="currentPagination.current"
                     :page-size="currentPagination.size"
                     :total="options.length"
                     layout="prev, pager, next">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import BCustomizedWidgetItem from './b-customized-widget-item.vue'
import { merge, isObject } from 'lodash'

const DEFAULT_PAGE = {
  current: 1,
  size: 12
}
export default {
  name: 'BCustomizedWidget',
  components: {
    BCustomizedWidgetItem
  },
  props: {
    pagination: true,
    rows: {
      type: [Number, String],
      default: 'auto-fit'
    },
    columns: {
      type: [Number, String],
      default: 'auto-fit'
    },
    options: {
      type: Array,
      default: () => ([])
    },
    itemStyle: {
      type: Object,
      default: () => ({
        width: '188px',
        height: '128px'
      })
    },
    position: {
      type: String,
      default: 'center'
    }
  },
  data () {
    return {
      currentPagination: isObject(this.pagination)
        ? merge(DEFAULT_PAGE, this.pagination, { size: this.rows * this.columns })
        : merge(DEFAULT_PAGE, { size: this.rows * this.columns })
    }
  },

  computed: {
    currentPosition () {
      if (this.position === 'left') {
        return 'justify-start'
      }
      if (this.position === 'center') {
        return 'justify-center'
      }
      if (this.position === 'right') {
        return 'justify-right'
      }
    }
  },
  methods: {
    onSelected (item) {
      this.$emit('event:change', item)
    }
  }
}
</script>

<style lang="scss" scoped>
.b-customized-widget {
  padding: 16px;

  &__wrapper {
    display: grid;
    grid-row-gap: 16px;
    grid-column-gap: 16px;
  }
  &-pagination {
    padding-top: 16px;
  }
}
</style>
